import React, { useState, useEffect } from 'react';
import { invoke } from '@tauri-apps/api/core';
import {
  DocumentTextIcon,
  TrashIcon,
  FunnelIcon,
  MagnifyingGlassIcon,
  ChartBarIcon,
  ExclamationTriangleIcon,
  InformationCircleIcon,
  XCircleIcon,
} from '@heroicons/react/24/outline';

interface LogEntry {
  id?: number;
  level: string;
  message: string;
  component?: string;
  metadata?: any;
  created_at: string;
}

interface LogStats {
  total: number;
  by_level?: Record<string, number>;
  recent_count: number;
}

const LOG_LEVELS = ['DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL'];
const LOG_LEVEL_COLORS = {
  DEBUG: 'text-gray-600 bg-gray-100 dark:bg-gray-800',
  INFO: 'text-blue-600 bg-blue-100 dark:bg-blue-900',
  WARN: 'text-yellow-600 bg-yellow-100 dark:bg-yellow-900',
  ERROR: 'text-red-600 bg-red-100 dark:bg-red-900',
  FATAL: 'text-purple-600 bg-purple-100 dark:bg-purple-900',
};

const LOG_LEVEL_ICONS = {
  DEBUG: InformationCircleIcon,
  INFO: InformationCircleIcon,
  WARN: ExclamationTriangleIcon,
  ERROR: XCircleIcon,
  FATAL: XCircleIcon,
};

const Logs: React.FC = () => {
  const [logs, setLogs] = useState<LogEntry[]>([]);
  const [stats, setStats] = useState<LogStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // 过滤和搜索状态
  const [levelFilter, setLevelFilter] = useState<string>('');
  const [searchQuery, setSearchQuery] = useState('');
  const [limit, setLimit] = useState(100);

  // 清理状态
  const [clearDays, setClearDays] = useState(7);
  const [clearing, setClearing] = useState(false);

  const loadLogs = async () => {
    try {
      setLoading(true);
      setError(null);

      const [logsData, statsData] = await Promise.all([
        invoke<LogEntry[]>('get_logs', {
          limit,
          levelFilter: levelFilter || null,
        }),
        invoke<LogStats>('get_log_stats'),
      ]);

      setLogs(logsData);
      setStats(statsData);
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setLoading(false);
    }
  };

  const clearLogs = async () => {
    try {
      setClearing(true);
      const deletedCount = await invoke<number>('clear_logs', {
        days: clearDays,
      });

      // 重新加载日志
      await loadLogs();

      alert(`已清理 ${deletedCount} 条日志记录`);
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setClearing(false);
    }
  };

  useEffect(() => {
    loadLogs();
  }, [limit, levelFilter]);

  // 过滤日志
  const filteredLogs = logs.filter(log => {
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      return (
        log.message.toLowerCase().includes(query) ||
        log.component?.toLowerCase().includes(query) ||
        log.level.toLowerCase().includes(query)
      );
    }
    return true;
  });

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleString('zh-CN');
  };

  if (loading) {
    return (
      <div className="flex h-64 items-center justify-center">
        <div className="h-8 w-8 animate-spin rounded-full border-b-2 border-blue-600"></div>
        <span className="ml-2">加载日志...</span>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100">
          日志管理
        </h1>
        <div className="flex space-x-2">
          <button
            onClick={loadLogs}
            className="flex items-center rounded bg-blue-600 px-4 py-2 text-white hover:bg-blue-700"
          >
            <DocumentTextIcon className="mr-2 h-4 w-4" />
            刷新
          </button>
        </div>
      </div>

      {error && (
        <div className="rounded-lg border border-red-200 bg-red-50 p-4 dark:border-red-800 dark:bg-red-900/20">
          <div className="flex items-center">
            <XCircleIcon className="mr-2 h-5 w-5 text-red-500" />
            <span className="text-red-700 dark:text-red-400">
              错误: {error}
            </span>
          </div>
        </div>
      )}

      {/* 统计信息 */}
      {stats && (
        <div className="rounded-lg border border-gray-200 bg-white p-6 dark:border-gray-700 dark:bg-gray-800">
          <h2 className="mb-4 flex items-center text-lg font-semibold">
            <ChartBarIcon className="mr-2 h-5 w-5 text-blue-500" />
            日志统计
          </h2>
          <div className="grid grid-cols-2 gap-4 md:grid-cols-4 lg:grid-cols-6">
            <div className="text-center">
              <div className="text-2xl font-bold text-gray-900 dark:text-gray-100">
                {stats?.total || 0}
              </div>
              <div className="text-sm text-gray-600 dark:text-gray-400">
                总计
              </div>
            </div>
            {Object.entries(stats?.by_level || {}).map(([level, count]) => (
              <div key={level} className="text-center">
                <div
                  className={`text-2xl font-bold ${LOG_LEVEL_COLORS[level as keyof typeof LOG_LEVEL_COLORS]?.split(' ')[0] || 'text-gray-900'}`}
                >
                  {count}
                </div>
                <div className="text-sm text-gray-600 dark:text-gray-400">
                  {level}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 过滤和搜索 */}
      <div className="rounded-lg border border-gray-200 bg-white p-4 dark:border-gray-700 dark:bg-gray-800">
        <div className="flex flex-wrap items-center gap-4">
          {/* 搜索 */}
          <div className="min-w-64 flex-1">
            <div className="relative">
              <MagnifyingGlassIcon className="absolute left-3 top-1/2 h-5 w-5 -translate-y-1/2 transform text-gray-400" />
              <input
                type="text"
                placeholder="搜索日志..."
                value={searchQuery}
                onChange={e => setSearchQuery(e.target.value)}
                className="w-full rounded-lg border border-gray-300 bg-white py-2 pl-10 pr-4 text-gray-900 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-100"
              />
            </div>
          </div>

          {/* 级别过滤 */}
          <div className="flex items-center space-x-2">
            <FunnelIcon className="h-5 w-5 text-gray-400" />
            <select
              value={levelFilter}
              onChange={e => setLevelFilter(e.target.value)}
              className="rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-100"
            >
              <option value="">所有级别</option>
              {LOG_LEVELS.map(level => (
                <option key={level} value={level}>
                  {level}
                </option>
              ))}
            </select>
          </div>

          {/* 数量限制 */}
          <div className="flex items-center space-x-2">
            <span className="text-sm text-gray-600 dark:text-gray-400">
              显示:
            </span>
            <select
              value={limit}
              onChange={e => setLimit(Number(e.target.value))}
              className="rounded-lg border border-gray-300 bg-white px-3 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-100"
            >
              <option value={50}>50</option>
              <option value={100}>100</option>
              <option value={200}>200</option>
              <option value={500}>500</option>
            </select>
          </div>

          {/* 清理日志 */}
          <div className="flex items-center space-x-2">
            <input
              type="number"
              value={clearDays}
              onChange={e => setClearDays(Number(e.target.value))}
              min="1"
              max="365"
              className="w-16 rounded-lg border border-gray-300 bg-white px-2 py-2 text-gray-900 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-100"
            />
            <span className="text-sm text-gray-600 dark:text-gray-400">
              天前
            </span>
            <button
              onClick={clearLogs}
              disabled={clearing}
              className="flex items-center rounded bg-red-600 px-3 py-2 text-white hover:bg-red-700 disabled:opacity-50"
            >
              <TrashIcon className="mr-1 h-4 w-4" />
              {clearing ? '清理中...' : '清理'}
            </button>
          </div>
        </div>
      </div>

      {/* 日志列表 */}
      <div className="rounded-lg border border-gray-200 bg-white dark:border-gray-700 dark:bg-gray-800">
        <div className="border-b border-gray-200 p-4 dark:border-gray-700">
          <h2 className="text-lg font-semibold">
            日志记录 ({filteredLogs.length})
          </h2>
        </div>

        <div className="max-h-96 overflow-y-auto">
          {filteredLogs.length === 0 ? (
            <div className="p-8 text-center text-gray-500 dark:text-gray-400">
              没有找到日志记录
            </div>
          ) : (
            <div className="divide-y divide-gray-200 dark:divide-gray-700">
              {filteredLogs.map((log, index) => {
                const IconComponent =
                  LOG_LEVEL_ICONS[log.level as keyof typeof LOG_LEVEL_ICONS] ||
                  InformationCircleIcon;
                const colorClass =
                  LOG_LEVEL_COLORS[
                    log.level as keyof typeof LOG_LEVEL_COLORS
                  ] || 'text-gray-600 bg-gray-100';

                return (
                  <div
                    key={log.id || index}
                    className="p-4 hover:bg-gray-50 dark:hover:bg-gray-700"
                  >
                    <div className="flex items-start space-x-3">
                      <IconComponent
                        className={`mt-0.5 h-5 w-5 ${colorClass.split(' ')[0]}`}
                      />
                      <div className="min-w-0 flex-1">
                        <div className="mb-1 flex items-center space-x-2">
                          <span
                            className={`rounded px-2 py-1 text-xs font-medium ${colorClass}`}
                          >
                            {log.level}
                          </span>
                          {log.component && (
                            <span className="rounded bg-gray-100 px-2 py-1 text-xs text-gray-600 dark:bg-gray-700 dark:text-gray-400">
                              {log.component}
                            </span>
                          )}
                          <span className="text-xs text-gray-500 dark:text-gray-400">
                            {formatDate(log.created_at)}
                          </span>
                        </div>
                        <div className="break-words text-sm text-gray-900 dark:text-gray-100">
                          {log.message}
                        </div>
                        {log.metadata && (
                          <details className="mt-2">
                            <summary className="cursor-pointer text-xs text-gray-500 dark:text-gray-400">
                              元数据
                            </summary>
                            <pre className="mt-1 overflow-x-auto rounded bg-gray-100 p-2 text-xs dark:bg-gray-700">
                              {JSON.stringify(log.metadata, null, 2)}
                            </pre>
                          </details>
                        )}
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default Logs;
